package com.ymatou.iapi.trading.sellerquery2.testcase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderService;
import com.ymatou.iapi.trading.operate.parameter.po.OrderInfoSubPo;
import com.ymatou.iapi.trading.operate.parameter.req.BizVo;
import com.ymatou.iapi.trading.operate.testcase.Ts_ChangeOrderBizStatus;
import com.ymatou.iapi.trading.sellerquery2.parameter.vo.SubProductInfo;
import com.ymatou.query.seller.trading.api.parameter.FundSummary;
import com.ymatou.query.seller.trading.api.parameter.GetSellerOrdersBean;
import com.ymatou.query.seller.trading.api.parameter.Pagination;
import com.ymatou.query.seller.trading.api.parameter.Sp_GetOrdersByOrderIds_v2;
import com.ymatou.query.seller.trading.api.parameter.Seller.Common;
import com.ymatou.query.seller.trading.api.parameter.info.OrderBasicInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderConsigneeInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderConsumerInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderPaymentDetail;
import com.ymatou.query.seller.trading.api.parameter.info.OrderPaymentInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderProductInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderSellerInfo;
import com.ymatou.query.seller.trading.api.parameter.info.OrderTransferInfo;
import com.ymatou.query.seller.trading.api.parameter.info.SellerOrderInfo;
import com.ymatou.query.seller.trading.api.parameter.resp.GetSellerOrdersResponse;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.common.enums.OrderQueryStatusEnum;
import com.ymttest.common.enums.OrderQueryTimeTypeEnum;
import com.ymttest.common.enums.OrderStatusEnum;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.ECode;

/**
 * 根据卖家ID批量查询订单 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_GetSellerOrders {
	private static GetSellerOrdersBean request;
	//	private static com.ymatou.query.seller.trading.api.service.GetSellerOrdersCall call;
	private static com.ymatou.iapi.trading.sellerquery2.service.GetSellerOrdersCall call;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("根据卖家ID批量查询订单");
	}

	@Before
	public void caseUp() {
		request = new GetSellerOrdersBean();
		//		call = new com.ymatou.query.seller.trading.api.service.GetSellerOrdersCall();
		call = new com.ymatou.iapi.trading.sellerquery2.service.GetSellerOrdersCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {

		GetSellerOrdersResponse expectedResponse = new GetSellerOrdersResponse();
		ConstructExpectedResponse(expectedResponse);
		GetSellerOrdersResponse actualResponse = call.getSellerOrdersResponse();

		DataUtil.verifyEquals(expectedResponse.getTotalOrdersCount(),
				actualResponse.getTotalOrdersCount(), "验证TotalOrdersCount");
		if (DataUtil.isNullOrEmpty(expectedResponse.getOrders())) {
			DataUtil.verifyEquals(true,
					DataUtil.isNullOrEmpty(actualResponse.getOrders()),
					"验证期望的Orders==null或空列表");
		} else {
			boolean goon = !DataUtil.isNullOrEmpty(actualResponse.getOrders());
			DataUtil.verifyEquals(true, goon, "验证期望的Orders!=null且不是空列表");

			if (goon) {

				DataUtil.verifyEquals(expectedResponse.getOrders().size(),
						actualResponse.getOrders().size(), "验证Orders的数量");
				boolean flag = expectedResponse.getOrders().size() == actualResponse
						.getOrders().size();

				if (flag) {
					for (int i = 0; i < expectedResponse.getOrders().size(); i++) {

						SellerOrderInfo expect = expectedResponse.getOrders()
								.get(i);

						int expectId = expect.getBasic().getID();
						// DataUtil.verifyEquals(expect.getBasic().getID(),
						// actualResponse.getOrders().get(i).getBasic()
						// .getID(), "验证Orders中第" + (i + 1) + "条记录的排序");
						boolean exists = expectedResponse
								.getOrders()
								.stream()
								.anyMatch(x -> x.getBasic().getID() == expectId);
						DataUtil.verifyEquals(true, exists,
								"验证Orders中存在Basic.ID=[" + expectId + "]的订单记录");

						if (exists) {

							SellerOrderInfo actual = actualResponse
									.getOrders()
									.stream()
									.filter(x -> x.getBasic().getID() == expectId)
									.collect(Collectors.toList()).get(0);

							verifySellerOrderInfo(expect, actual, expectId);

						}
					}
				}
			}
		}
	}

	public static void verifySellerOrderInfo(SellerOrderInfo expect,
			SellerOrderInfo actual, int expectId) {
		OrderBasicInfo expBasic = expect.getBasic();
		OrderBasicInfo actBasic = actual.getBasic();
		verifyBasic(expBasic, actBasic, expectId);
		OrderConsumerInfo expBuyer = expect.getBuyer();
		OrderConsumerInfo actBuyer = actual.getBuyer();
		verifyBuyer(expBuyer, actBuyer, expectId);
		OrderConsigneeInfo expConsignee = expect.getConsignee();
		OrderConsigneeInfo actConsignee = actual.getConsignee();
		verifyConsignee(expConsignee, actConsignee, expectId);
		OrderPaymentInfo expPayment = expect.getPayment();
		OrderPaymentInfo actPayment = actual.getPayment();
		verifyPayment(expPayment, actPayment, expectId);
		OrderSellerInfo expSeller = expect.getSeller();
		OrderSellerInfo actSeller = actual.getSeller();
		verifySeller(expSeller, actSeller, expectId);
		OrderTransferInfo expTransfer = expect.getTransfer();
		OrderTransferInfo actTransfer = actual.getTransfer();
		verifyTransfer(expTransfer, actTransfer, expectId);

		List<OrderProductInfo> expProducts = expect.getProducts();
		List<OrderProductInfo> actProducts = actual.getProducts();

		verifyProducts(expProducts, actProducts, expectId);

		//校验组合商品
		verifySubProducts(expectId, actProducts);
	}
	/**
	 * 校验砍价团状态
	 * 
	 * */
	private static void verifyBizStaute() {

		List<SellerOrderInfo> orderList = call.getSellerOrdersResponse()
				.getOrders();

		if (orderList.size() > 0) {
			for (SellerOrderInfo sellerOrderInfo : orderList) {

				BizVo biz = Ts_ChangeOrderBizStatus
						.getBizVosByOrderId(sellerOrderInfo.getBasic().getID());

				if (null == biz)
					continue;
				Logger.verifyEquals(3, biz.getBizStatus(),
						"验证砍价团状态为BizStatus=3");
			}

		}

	}
	private static void verifyProducts(List<OrderProductInfo> expect,
			List<OrderProductInfo> actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Products对象");
		if (null == expect) {
			DataUtil.verifyDateEquals(null, actual, "验证id=[" + expectId
					+ "]Products=null");
		} else {
			DataUtil.verifyEquals(expect.size(), actual.size(), "验证id=["
					+ expectId + "]Products.size()");
			boolean flag = expect.size() == expect.size();
			if (flag) {

				for (OrderProductInfo exp : expect) {

					String expPid = exp.getProductId();
					boolean exists = actual.stream().anyMatch(
							x -> x.getProductId().equals(expPid));
					DataUtil.verifyEquals(true, exists, "验证id=[" + expectId
							+ "]的ProductId=[" + expPid + "]的Product记录是否存在");

					if (exists) {
						DataUtil.verify(true,
								actual.stream().anyMatch(x -> x.equals(exp)),
								"验证\n" + exp + "\n是否存在于id=[" + expectId
										+ "]的products中");
					}

				}
			}
		}
		Logger.comment("完成验证id=[" + expectId + "]的Products对象");
	}

	/**
	 * 校验组合商品
	 * @param expectId
	 * @param actProducts
	 */
	private static void verifySubProducts(int expectId,
			List<OrderProductInfo> actProducts) {

		DefaultWapper data = new DefaultWapper();

		try {
			for (OrderProductInfo pro : actProducts) {

				String catalogId = pro.getCatalogId();

				List<SubProductInfo> actualOrderInfoSub = pro
						.getSubProductInfos();

				List<OrderInfoSubPo> expectOrderInfoSub = data.getOrderInfoSub(
						expectId, catalogId);

				DataUtil.verifyEquals(expectOrderInfoSub.size(),
						actualOrderInfoSub.size(), "验证id=[" + expectId
								+ "]Products 下组合商品记录数");

				boolean flag = expectOrderInfoSub.size() == actualOrderInfoSub
						.size();

				if (flag) {
					Logger.comment("开始验证catalogId=[" + catalogId
							+ "]的Products下的组合商品");

					for (int i = 0; i < expectOrderInfoSub.size(); i++) {

						OrderInfoSubPo expect = expectOrderInfoSub.get(i);
						SubProductInfo actual = actualOrderInfoSub.get(i);

						Logger.verifyEquals(expect.getSubTitle(),
								actual.getSubTitle(), "校验组合商品 subTitle");
						Logger.verifyEquals(expect.getSubCatalogId(),
								actual.getSubCatalogId(), "校验组合商品 subCatalogId");
						Logger.verifyEquals(expect.getFirstCatId(),
								actual.getFirstCatId(), "校验组合商品 firstCatId");

						Logger.verifyEquals(expect.getSecondCatId(),
								actual.getSecondCatId(), "校验组合商品 secondCatId");

						Logger.verifyEquals(expect.getThirdCatId(),
								actual.getThirdCatId(), "校验组合商品 thirdCatId");

						Logger.verifyEquals(expect.getNum(), actual.getNum(),
								"校验组合商品 num");

						DataUtil.verifyDecimalEquals(expect.getOriginalPrice(),
								actual.getOriginalPrice(),
								"校验组合商品 originalPrice");

						DataUtil.verifyDecimalEquals(expect.getPrice(),
								actual.getPrice(), "校验组合商品 price");

						DataUtil.verifyDecimalEquals(expect.getFreight(),
								actual.getFreight(), "校验组合商品 freight");

						DataUtil.verifyDecimalEquals(expect.getDiscount(),
								actual.getDiscount(), "校验组合商品 discount");

						DataUtil.verifyDecimalEquals(expect.getYmtCoupon(),
								actual.getYmtCoupon(), "校验组合商品 ymtCoupon");

						DataUtil.verifyDecimalEquals(expect.getSellerCoupon(),
								actual.getSellerCoupon(), "校验组合商品 sellerCoupon");

						DataUtil.verifyDecimalEquals(
								expect.getThirdPartyDiscount(),
								actual.getThirdPartyDiscount(),
								"校验组合商品 thirdPartyDiscount");

						DataUtil.verifyDecimalEquals(expect.getPromotion(),
								actual.getPromotion(), "校验组合商品  promotion");

					}

				}

			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	private static Date getDate(String s) {
		if (null != s && "".equals(s) == false) {
			s = s.replaceAll("T", " ");
		}
		return YMTDateUtil.parseDate(s, YMTDateUtil.YMDHMS);
	}

	private static void verifyTransfer(OrderTransferInfo expect,
			OrderTransferInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Transfer对象");
		DataUtil.verifyDateEquals(expect.getDeliveredTime(),
				actual.getDeliveredTime(), "验证id=[" + expectId
						+ "]Transfer.DeliveredTime");
		DataUtil.verifyDateEquals(expect.getReceiptConfirmedTime(),
				actual.getReceiptConfirmedTime(), "验证id=[" + expectId
						+ "]Transfer.ReceiptConfirmedTime");
		Logger.comment("完成验证id=[" + expectId + "]的Transfer对象");
	}

	private static void verifySeller(OrderSellerInfo expect,
			OrderSellerInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Seller对象");
		DataUtil.verify(DataUtil.Stringg.getValueOrDefault(DataUtil.Stringg
				.getValueOrDefault(expect.getComment())), DataUtil.Stringg
				.getValueOrDefault(actual.getComment()), "验证id=[" + expectId
				+ "]Seller.Comment");
		//		DataUtil.verifyEquals(expect.getEmail(), actual.getEmail(), "验证id=["
		//				+ expectId + "]Seller.Email");
		DataUtil.verifyEquals(expect.getID(), actual.getID(), "验证id=["
				+ expectId + "]Seller.ID");
		DataUtil.verifyEquals(expect.getLoginId(), actual.getLoginId(),
				"验证id=[" + expectId + "]Seller.LoginId");
		Logger.comment("完成验证id=[" + expectId + "]的Seller对象");
	}

	private static void verifyPayment(OrderPaymentInfo expect,
			OrderPaymentInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Payment对象");
		DataUtil.verifyDecimalEquals(expect.getActualPaid(),
				actual.getActualPaid(), "验证id=[" + expectId
						+ "]的Payment.ActualPaid");
		List<OrderPaymentDetail> expDetails = expect.getDetails();
		List<OrderPaymentDetail> actDetails = actual.getDetails();
		if (expDetails == null) {
			DataUtil.verifyEquals(true, DataUtil.isNullOrEmpty(actDetails),
					"验证id=[" + expectId + "]的Payment.Details == null或者空list");
		} else {
			boolean flag = expDetails.size() == actDetails.size();
			DataUtil.verifyEquals(expDetails.size(), actDetails.size(),
					"验证id=[" + expectId + "]的Payment.Details的Size()");
			if (flag) {
				for (OrderPaymentDetail exp : expDetails) {
					// for (int i=0;i< expDetails.size();i++) {
					// OrderPaymentDetail exp = expDetails.get(i);
					String expTime = exp.getPaidTime();
					Date expTimeDate = getDate(expTime);
					boolean exists = actDetails.stream().anyMatch(
							x -> getDate(x.getPaidTime())
									.compareTo(expTimeDate) == 0
									&& exp.getType() == x.getType());
					DataUtil.verifyEquals(expDetails.size(), actDetails.size(),
							"验证id=[" + expectId + "]的PaidTime=[" + expTime
									+ "]Payment.Details的记录是否存在()");
					if (exists) {
						OrderPaymentDetail act = actDetails
								.stream()
								.filter(x -> getDate(x.getPaidTime())
										.compareTo(expTimeDate) == 0
										&& exp.getType() == x.getType())
								.collect(Collectors.toList()).get(0);
						DataUtil.verifyEquals(exp.getExternalTradingNo(),
								act.getExternalTradingNo(), "验证id=[" + expectId
										+ "]的PaidTime=[" + expTime
										+ "]Payment.Details.ExternalTradingNo");
						DataUtil.verifyEquals(exp.getInternalTradingNo(),
								act.getInternalTradingNo(), "验证id=[" + expectId
										+ "]的PaidTime=[" + expTime
										+ "]Payment.Details.InternalTradingNo");
						DataUtil.verifyEquals(exp.getType(), act.getType(),
								"验证id=[" + expectId + "]的PaidTime=[" + expTime
										+ "]Payment.Details.Type");
					}
				}
			}
		}
		FundSummary expSummary = expect.getSummary();
		FundSummary actSummary = actual.getSummary();
		DataUtil.verify(expSummary.getFirstPayProductPrice(),
				actSummary.getFirstPayProductPrice(), "验证id=[" + expectId
						+ "]的Payment.Summary.FirstPayProductPrice");
		DataUtil.verify(expSummary.getFreight(), actSummary.getFreight(),
				"验证id=[" + expectId + "]的Payment.Summary.Freight");
		DataUtil.verify(expSummary.getOrderDiscount(),
				actSummary.getOrderDiscount(), "验证id=[" + expectId
						+ "]的Payment.Summary.OrderDiscount");
		DataUtil.verify(expSummary.getPaidCash(), actSummary.getPaidCash(),
				"验证id=[" + expectId + "]的Payment.Summary.PaidCash");
		DataUtil.verify(expSummary.getPaidFreeCard(),
				actSummary.getPaidFreeCard(), "验证id=[" + expectId
						+ "]的Payment.Summary.PaidFreeCard");
		DataUtil.verify(expSummary.getPaidGift(), actSummary.getPaidGift(),
				"验证id=[" + expectId + "]的Payment.Summary.PaidGift");
		DataUtil.verify(expSummary.getPaidSellerCoupon(),
				actSummary.getPaidSellerCoupon(), "验证id=[" + expectId
						+ "]的Payment.Summary.PaidSellerCoupon");
		DataUtil.verify(expSummary.getPaidYmtCoupon(),
				actSummary.getPaidYmtCoupon(), "验证id=[" + expectId
						+ "]的Payment.Summary.PaidYmtCoupon");
		DataUtil.verify(expSummary.getPostPaidCash(),
				actSummary.getPostPaidCash(), "验证id=[" + expectId
						+ "]的Payment.Summary.PostPaidCash");
		DataUtil.verify(expSummary.getPostPaidGift(),
				actSummary.getPostPaidGift(), "验证id=[" + expectId
						+ "]的Payment.Summary.PostPaidGift");
		DataUtil.verify(expSummary.getPostPayDiscount(),
				actSummary.getPostPayDiscount(), "验证id=[" + expectId
						+ "]的Payment.Summary.PostPayDiscount");
		DataUtil.verify(expSummary.getTotalActivityPrice(),
				actSummary.getTotalActivityPrice(), "验证id=[" + expectId
						+ "]的Payment.Summary.TotalActivityPrice");
		DataUtil.verify(expSummary.getTotalCanceledCash(),
				actSummary.getTotalCanceledCash(), "验证id=[" + expectId
						+ "]的Payment.Summary.TotalCanceledCash");
		DataUtil.verify(expSummary.getTotalCanceledYmtCoupon(),
				actSummary.getTotalCanceledYmtCoupon(), "验证id=[" + expectId
						+ "]的Payment.Summary.TotalCanceledYmtCoupon");
		DataUtil.verify(expSummary.getTotalProductPrice(),
				actSummary.getTotalProductPrice(), "验证id=[" + expectId
						+ "]的Payment.Summary.TotalProductPrice");
		DataUtil.verify(DataUtil.BigDecimall.GetValueOrDefault(expSummary
				.getTotalRefundedCash()), actSummary.getTotalRefundedCash(),
				"验证id=[" + expectId + "]的Payment.Summary.TotalRefundedCash");
		DataUtil.verify(DataUtil.BigDecimall.GetValueOrDefault(expSummary
				.getTotalRefundedGift()), actSummary.getTotalRefundedGift(),
				"验证id=[" + expectId + "]的Payment.Summary.TotalRefundedGift");
		DataUtil.verify(DataUtil.BigDecimall.GetValueOrDefault(expSummary
				.getTotalRefundedYmtCoupon()), actSummary
				.getTotalRefundedYmtCoupon(), "验证id=[" + expectId
				+ "]的Payment.Summary.TotalRefundedYmtCoupon");

		Logger.comment("完成验证id=[" + expectId + "]的Payment对象");
	}

	private static void verifyConsignee(OrderConsigneeInfo expect,
			OrderConsigneeInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Consignee对象");
		DataUtil.verifyEquals(expect.getAddress(), actual.getAddress(),
				"验证id=[" + expectId + "]的Consignee.Address");
		DataUtil.verifyEquals(expect.getName(), actual.getName(), "验证id=["
				+ expectId + "]的Consignee.Name");
		DataUtil.verifyEquals(expect.getPhone(), actual.getPhone(), "验证id=["
				+ expectId + "]的Consignee.Phone");
		DataUtil.verifyEquals(expect.getPostcode(), actual.getPostcode(),
				"验证id=[" + expectId + "]的Consignee.Postcode");
		DataUtil.verifyEquals(expect.getTel(), actual.getTel(), "验证id=["
				+ expectId + "]的Consignee.Tel");
		Logger.comment("完成验证id=[" + expectId + "]的Consignee对象");
	}

	private static void verifyBuyer(OrderConsumerInfo expect,
			OrderConsumerInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Buyer对象");
		DataUtil.verifyEquals(expect.getEmail(), actual.getEmail(), "验证id=["
				+ expectId + "]的Buyer.Email");
		DataUtil.verifyEquals(expect.getID(), actual.getID(), "验证id=["
				+ expectId + "]的Buyer.ID");
		DataUtil.verifyEquals(expect.getLoginId(), actual.getLoginId(),
				"验证id=[" + expectId + "]的Buyer.LoginId");
		DataUtil.verifyEquals(expect.getMessage(), actual.getMessage(),
				"验证id=[" + expectId + "]的Buyer.Message");
		DataUtil.verifyEquals(expect.getNickName(), actual.getNickName(),
				"验证id=[" + expectId + "]的Buyer.NickName");
		Logger.comment("完成验证id=[" + expectId + "]的Buyer对象");
	}

	private static void verifyBasic(OrderBasicInfo expect,
			OrderBasicInfo actual, int expectId) {
		Logger.comment("开始验证id=[" + expectId + "]的Basic对象");
		DataUtil.verifyDateEquals(expect.getAcceptedTime(),
				actual.getAcceptedTime(), "验证id=[" + expectId
						+ "]的Basic.AcceptedTime");
		DataUtil.verifyDateEquals(expect.getCancelledTime(),
				actual.getCancelledTime(), "验证id=[" + expectId
						+ "]的Basic.CancelledTime");
		DataUtil.verifyDateEquals(expect.getCreatedTime(),
				actual.getCreatedTime(), "验证id=[" + expectId
						+ "]的Basic.CreatedTime");
		DataUtil.verifyDecimalEquals(expect.getDiscount(),
				actual.getDiscount(), "验证id=[" + expectId + "]的Basic.Discount");
		DataUtil.verifyEquals(expect.getSource(), actual.getSource(), "验证id=["
				+ expectId + "]的Basic.Source");
		DataUtil.verifyEquals(expect.getStatus(), actual.getStatus(), "验证id=["
				+ expectId + "]的Basic.Status");
		DataUtil.verifyDecimalEquals(expect.getTotalPrice(),
				actual.getTotalPrice(), "验证id=[" + expectId
						+ "]的Basic.TotalPrice");
		//		DataUtil.verifyEquals(expect.getType(), actual.getType(), "验证id=["
		//				+ expectId + "]的Basic.Type");
		Logger.comment("完成验证id=[" + expectId + "]的Basic对象");
	}

	private void ConstructExpectedResponse(GetSellerOrdersResponse response) {
		Process(response);
	}

	private String time = "dAddTime";

	@SuppressWarnings("rawtypes")
	private void Process(GetSellerOrdersResponse response) {

		DefaultWapper db = new DefaultWapper();

		Pagination page = new Pagination(request.getPageIndex(),
				request.getPageSize());
		int status = DataUtil.Integerr.GetValueOrDefault(request
				.getOrderStatus());
		int skip = page.getPageItemIndexFrom() - 1;
		int limit = page.getPageSize();

		String total = getTotalSQL(GetStatusCondition(status), skip, limit,
				GetTimeTypeField(request.getTimeType()),
				GetPaidInFullCondition(status),
				GetLogisticsCondition(request.getLogistics()));
		response.setTotalOrdersCount((int) db.executeSql(total).get(0)
				.get("Total"));
		String orderSql = getOrdersSQL(GetStatusCondition(status), skip, limit,
				GetTimeTypeField(request.getTimeType()),
				GetPaidInFullCondition(status),
				GetLogisticsCondition(request.getLogistics()));

		List<Map> rs = db.executeSql(orderSql);

		Sp_GetOrdersByOrderIds_v2 result = null;

		if (!DataUtil.isNullOrEmpty(rs)) {
			List<Integer> iOrderIds = new ArrayList<Integer>();
			for (Map m : rs) {
				iOrderIds.add((int) m.get("orderid"));
			}
			Sp_GetOrdersByOrderIds_v2 sp = new Sp_GetOrdersByOrderIds_v2();
			sp.setOrders(iOrderIds);
			sp.setSeller(request.getSellerId());
			result = sp.execute();
		}

		List<SellerOrderInfo> orders = Common.ConvertToSellerOrders(result);

		response.setOrders(orders);
	}

	private StringBuilder getCommon(int status, int skip, int limit,
			String timeType, String condi2, String condi3) {
		StringBuilder sb = new StringBuilder();
		DataUtil.SQL.declareVarOfSp("i", sb, "status", status);
		DataUtil.SQL.declareVarOfSp("i", sb, "seller", request.getSellerId());
		DataUtil.SQL.declareVarOfSp("dt", sb, "beginTime",
				request.getBeginTime());
		DataUtil.SQL.declareVarOfSp("dt", sb, "endTime", request.getEndTime());
		DataUtil.SQL.declareVarOfSp("i", sb, "skip", skip);
		DataUtil.SQL.declareVarOfSp("i", sb, "limit", limit);
		return sb;
	}

	private String getOrdersSQL(int status, int skip, int limit,
			String timeType, String condi2, String condi3) {
		StringBuilder sb = getCommon(status, skip, limit, timeType, condi2,
				condi3);
		sb.append("; declare @orders Int32Array;");
		sb.append(" insert into @orders select o.iOrderId from Ymt_Orders(nolock) o where iBuyerId = @seller");
		sb.append(" and iTradingStatus = @status and " + timeType
				+ " >= @beginTime and " + timeType + " < @endTime");
		sb.append(condi2);
		sb.append(condi3);

		sb.append(" order by " + timeType + " desc");
		sb.append(" offset @skip rows fetch next @limit rows only");
		sb.append(" select value as orderid from @orders");
		return sb.toString();
	}

	private String getTotalSQL(int status, int skip, int limit,
			String timeType, String condi2, String condi3) {
		StringBuilder sb = getCommon(status, skip, limit, timeType, condi2,
				condi3);
		sb.append(" select count(1) as Total from Ymt_Orders(nolock) o");
		sb.append(" where iBuyerId = @seller");
		sb.append(" and iTradingStatus = @status");
		sb.append(" and " + timeType + " >= @beginTime and " + timeType
				+ " < @endTime");
		sb.append(condi2);
		sb.append(condi3);
		return sb.toString();
	}

	private static int GetStatusCondition(int status) {
		if (status == OrderStatusEnum.SellerAccept.getValue()) {
			return 17;
		} else if (status == OrderStatusEnum.OrderPostPay.getValue()) {
			return 17;
		}

		return status;
	}

	private static String GetTimeTypeField(int timeType) {
		switch (timeType) {
			case 2 :
				return " dPaidTime";
			case 5 :
				return " dAcceptTime";
		}
		return " dAddTime";
	}

	private static String GetPaidInFullCondition(int status) {
		//		if (status == OrderStatusEnum.SellerAccept.getValue()) {
		//			return " and bPaidInFull=1";
		//		} else if (status == OrderStatusEnum.OrderPostPay.getValue()) {
		//			return " and bPaidInFull=0";
		//		}

		return DataUtil.Stringg.Empty;
	}

	private static String GetLogisticsCondition(List<Integer> logisticsTypes) {
		if (DataUtil.isNullOrEmpty(logisticsTypes))
			return DataUtil.Stringg.Empty;
		List<Integer> logistics = logisticsTypes.stream().distinct()
				.collect(Collectors.toList());
		StringBuilder cond = new StringBuilder(
				" and exists(select top 1 1 from ymt_orderinfo(nolock) i where i.iorderid = o.iorderid and i.icatalogstatus ");
		if (logistics.size() > 1) {
			cond.append(" in " + DataUtil.toInOfSql(logistics));
		} else {
			cond.append(" = ").append(logistics.get(0));
		}
		return cond.append(")").toString();
	}

	// 根据总记录数，每页数 计算总共有多少页
	/*	private int getTotalPage(int totalRecords, int pageSize) {
			int totalPage;
			if (totalRecords % pageSize > 0) {
				totalPage = (totalRecords / pageSize) + 1;
			} else {
				totalPage = (totalRecords / pageSize);
			}
			return totalPage;
		}*/

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrders_001() {
		Logger.start(true, "根据卖家ID批量查询订单成功");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.OrderEstablish.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-20,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.CreateDate.getValue();
			request.setTimeType(timeType);
			request.setPageIndex(1);
			request.setPageSize(10);
			call.setData(request);
			call.callService();
			Logger.verifyEquals(ECode.SUCCESS, call.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrders_002() {
		Logger.start(true, "根据卖家ID+按下单时间查询");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.Received.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-20,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);

			int timeType = OrderQueryTimeTypeEnum.CreateDate.getValue();

			request.setTimeType(timeType);
			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.SUCCESS, call.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrders_003() {
		Logger.start(true, "验证第二页数据");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.AccountPaid.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-15,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);
			int pageSize = 2;
			request.setPageIndex(2);
			request.setPageSize(pageSize);
			call.setData(request);
			call.callService();
			verify();

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrders_004() {
		Logger.start(true, "根据卖家ID+状态等待发货+按付款时间查询");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-20,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);

			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();

			request.setTimeType(timeType);
			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.SUCCESS, call.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetSellerOrders_007() {
		Logger.start(true, "验证第二页和最后一页数据");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.AccountPaid.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-10,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(2,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);
			int pageSize = 2;

			request.setPageIndex(1);
			request.setPageSize(pageSize);
			call.setData(request);
			call.callService();

			int totalCount = call.getSellerOrdersResponse()
					.getTotalOrdersCount();
			int pageIndex = (int) Math.round((double) totalCount / pageSize);
			request.setPageIndex(pageIndex);
			request.setPageSize(pageSize);
			call.setData(request);
			call.callService();
			verify();

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_008() {
		Logger.start(false, "卖家id为null");
		try {
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-5,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(10,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_009() {
		Logger.start(false, "卖家id为0");
		try {
			request.setSellerId(0);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-5,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(10,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_010() {
		Logger.start(false, "订单状态为null");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			request.setSellerId(sellerId);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-5,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(10,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_011() {
		Logger.start(false, "时间类型为null");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-5,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(10,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);

			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_012() {
		Logger.start(false, "截止时间小于查询开始时间");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(1,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-1,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_013() {
		Logger.start(false, "查询指定当前页数为0");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-1,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(5,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);
			// request.setOrderType(orderType);

			request.setPageIndex(0);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_014() {
		Logger.start(false, "指定的每页显示条数超过200条");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			request.setSellerId(sellerId);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-20,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(201);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_015() {
		Logger.start(false, "指定的每页显示条数为0条");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.SellerAccept.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-1,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(5,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.PayDate.getValue();
			request.setTimeType(timeType);

			request.setPageIndex(1);
			request.setPageSize(0);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.ERROR400, call.getCode(), "验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_017() {
		Logger.start(true, "根据卖家ID批量查询订单成功, 商品有退货信息");
		try {
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));

			request.setSellerId(sellerId);
			int status = OrderQueryStatusEnum.Received.getValue();
			request.setOrderStatus(status);
			String beginTime = YMTDateUtil.getBeforeOrNextDay(-50,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(-20,
					YMTDateUtil.YMDTHMS_STRING);
			request.setBeginTime(beginTime);
			request.setEndTime(endTime);
			int timeType = OrderQueryTimeTypeEnum.CreateDate.getValue();
			request.setTimeType(timeType);
			request.setPageIndex(1);
			request.setPageSize(10);
			call.setData(request);
			call.callService();
			Logger.verifyEquals(ECode.SUCCESS, call.getCode(), "验证Code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetSellerOrders_018() {
		Logger.start(true, "根据卖家ID批量查询订单成功,订单含有组合商品");
		try {

			PlaceOrderResp placeOrder = PlaceOrderService.placeOrder10();

			request.setSellerId(placeOrder.getOrderList().get(0).getSellerId());

			int status = OrderQueryStatusEnum.OrderEstablish.getValue();

			request.setOrderStatus(status);

			String beginTime = YMTDateUtil.getBeforeOrNextDay(-1,
					YMTDateUtil.YMDTHMS_STRING);
			String endTime = YMTDateUtil.getBeforeOrNextDay(1,
					YMTDateUtil.YMDTHMS_STRING);

			request.setBeginTime(beginTime);
			request.setEndTime(endTime);

			int timeType = OrderQueryTimeTypeEnum.CreateDate.getValue();

			request.setTimeType(timeType);
			request.setPageIndex(1);
			request.setPageSize(10);

			call.setData(request);
			call.callService();

			Logger.verifyEquals(ECode.SUCCESS, call.getCode(), "验证Code");

			verify();

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}